<template>
  <div class="app-container">
    <div class="page-header">
      <h2 class="page-title">商品分类</h2>
    </div>

    <div class="category-container">
      <!-- 左侧：一级分类 -->
      <div class="left-panel">
        <div class="panel-header">
          <h3>一级分类</h3>
        </div>

        <!-- 添加一级分类 -->
        <div class="add-section">
          <el-input
            v-model="newCategory1.name"
            placeholder="一级分类"
            class="category-input"
          />
          <el-button type="primary" @click="addCategory1">添加</el-button>
        </div>

        <!-- 一级分类列表 -->
        <div class="category-list">
          <el-table :data="category1List" border>
            <el-table-column prop="name" label="一级分类" />
            <el-table-column prop="display_order" label="排序" width="80" />
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="editCategory1(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="deleteCategory1(scope.row)"
                >
                  删除
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="selectCategory1(scope.row)"
                >
                  子类列表
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 右侧：子分类 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>子分类</h3>
        </div>

        <!-- 子分类列表 -->
        <div class="category-list">
          <el-table :data="category2TableData" border>
            <el-table-column label="子分类">
              <template slot-scope="scope">
                <el-input
                  v-if="scope.row.isAddRow"
                  v-model="newCategory2.name"
                  placeholder="子分类名称"
                  size="small"
                />
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="排序" width="80">
              <template slot-scope="scope">
                <el-input
                  v-if="scope.row.isAddRow"
                  v-model="newCategory2.display_order"
                  placeholder="排序"
                  type="number"
                  size="small"
                />
                <span v-else>{{ scope.row.display_order }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <template v-if="scope.row.isAddRow">
                  <el-button type="primary" size="mini" @click="addCategory2">
                    添加
                  </el-button>
                  <el-button size="mini" @click="cancelAddCategory2">
                    取消
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    type="text"
                    size="mini"
                    @click="editCategory2(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="deleteCategory2(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 编辑一级分类对话框 -->
    <el-dialog
      title="编辑一级分类"
      :visible.sync="editCategory1Dialog"
      width="400px"
    >
      <el-form :model="editCategory1Form" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="editCategory1Form.name" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="editCategory1Form.display_order" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editCategory1Dialog = false">取消</el-button>
        <el-button type="primary" @click="saveCategory1">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑子分类对话框 -->
    <el-dialog
      title="编辑子分类"
      :visible.sync="editCategory2Dialog"
      width="400px"
    >
      <el-form :model="editCategory2Form" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="editCategory2Form.name" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="editCategory2Form.display_order" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editCategory2Dialog = false">取消</el-button>
        <el-button type="primary" @click="saveCategory2">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoryList,
  createProductCate,
  updateProductCate,
  deleteProductCate
} from "@/api/product";

export default {
  name: "ProductCate",
  data() {
    return {
      // 一级分类数据
      category1List: [],
      newCategory1: {
        name: "",
        display_order: 0
      },

      // 子分类数据
      category2List: [],
      newCategory2: {
        name: "",
        display_order: 0,
        parent_id: null
      },

      // 当前选中的一级分类
      selectedCategory1: null,

      // 编辑对话框
      editCategory1Dialog: false,
      editCategory2Dialog: false,
      editCategory1Form: {
        id: null,
        name: "",
        display_order: 0
      },
      editCategory2Form: {
        id: null,
        name: "",
        display_order: 0,
        parent_id: null
      }
    };
  },

  computed: {
    // 生成包含添加行的子分类表格数据
    category2TableData() {
      const addRow = {
        isAddRow: true,
        id: "add-row"
      };

      if (this.selectedCategory1) {
        return [addRow, ...this.category2List];
      }
      return this.category2List;
    }
  },

  created() {
    this.loadCategory1List();
  },

  methods: {
    // 加载一级分类列表
    async loadCategory1List() {
      try {
        const response = await getCategoryList({ level: 1 });
        console.log(response);
        this.category1List = response.data.list || [];
      } catch (error) {
        this.$message.error("加载一级分类失败");
      }
    },

    // 加载子分类列表
    async loadCategory2List(parentId) {
      try {
        const response = await getCategoryList({ parent_id: parentId });
        this.category2List = response.data.list || [];
      } catch (error) {
        this.$message.error("加载子分类失败");
      }
    },

    // 添加一级分类
    async addCategory1() {
      if (!this.newCategory1.name.trim()) {
        this.$message.warning("请输入分类名称");
        return;
      }

      try {
        await createProductCate({
          name: this.newCategory1.name,
          display_order: this.newCategory1.display_order,
          level: 1,
          parent_id: 0
        });
        this.$message.success("添加成功");
        this.newCategory1.name = "";
        this.newCategory1.display_order = 0;
        this.loadCategory1List();
      } catch (error) {
        this.$message.error("添加失败");
      }
    },

    // 添加子分类
    async addCategory2() {
      if (!this.newCategory2.name.trim()) {
        this.$message.warning("请输入分类名称");
        return;
      }

      if (!this.selectedCategory1) {
        this.$message.warning("请先选择一级分类");
        return;
      }

      try {
        await createProductCate({
          name: this.newCategory2.name,
          display_order: this.newCategory2.display_order,
          level: 2,
          parent_id: this.selectedCategory1.id
        });
        this.$message.success("添加成功");
        this.cancelAddCategory2();
        this.loadCategory2List(this.selectedCategory1.id);
      } catch (error) {
        this.$message.error("添加失败");
      }
    },

    // 取消添加子分类
    cancelAddCategory2() {
      this.newCategory2.name = "";
      this.newCategory2.display_order = 0;
    },

    // 选择一级分类
    selectCategory1(category) {
      this.selectedCategory1 = category;
      this.loadCategory2List(category.id);
    },

    // 编辑一级分类
    editCategory1(row) {
      this.editCategory1Form = {
        id: row.id,
        name: row.name,
        display_order: row.display_order
      };
      this.editCategory1Dialog = true;
    },

    // 保存一级分类
    async saveCategory1() {
      try {
        await updateProductCate(this.editCategory1Form.id, {
          name: this.editCategory1Form.name,
          display_order: this.editCategory1Form.display_order
        });
        this.$message.success("更新成功");
        this.editCategory1Dialog = false;
        this.loadCategory1List();
      } catch (error) {
        this.$message.error("更新失败");
      }
    },

    // 编辑子分类
    editCategory2(row) {
      this.editCategory2Form = {
        id: row.id,
        name: row.name,
        display_order: row.display_order,
        parent_id: row.parent_id
      };
      this.editCategory2Dialog = true;
    },

    // 保存子分类
    async saveCategory2() {
      try {
        await updateProductCate(this.editCategory2Form.id, {
          name: this.editCategory2Form.name,
          display_order: this.editCategory2Form.display_order
        });
        this.$message.success("更新成功");
        this.editCategory2Dialog = false;
        this.loadCategory2List(this.selectedCategory1.id);
      } catch (error) {
        this.$message.error("更新失败");
      }
    },

    // 删除一级分类
    deleteCategory1(row) {
      this.$confirm("确定要删除这个分类吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        try {
          await deleteProductCate(row.id);
          this.$message.success("删除成功");
          this.loadCategory1List();
          // 如果删除的是当前选中的分类，清空子分类列表
          if (this.selectedCategory1 && this.selectedCategory1.id === row.id) {
            this.selectedCategory1 = null;
            this.category2List = [];
          }
        } catch (error) {
          this.$message.error("删除失败");
        }
      });
    },

    // 删除子分类
    deleteCategory2(row) {
      this.$confirm("确定要删除这个分类吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        try {
          await deleteProductCate(row.id);
          this.$message.success("删除成功");
          this.loadCategory2List(this.selectedCategory1.id);
        } catch (error) {
          this.$message.error("删除失败");
        }
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.category-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
}

.left-panel,
.right-panel {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 20px 20px 0;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.add-section {
  padding: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
  border-bottom: 1px solid #e4e7ed;
}

.category-input {
  flex: 1;
}

.sort-input {
  width: 100px;
}

.category-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.category-list .el-table {
  height: 100%;
}

.category-list .el-table th,
.category-list .el-table td {
  padding: 12px 8px;
}

.left-panel .category-list .el-table {
  height: calc(100% - 120px);
}

.right-panel .category-list .el-table {
  height: calc(100% - 120px);
}
</style>
